<template>
  <div>
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <!-- <div>
        <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
        <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button>
      </div> -->
      <pure-table :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
        @selection-change="selectionChange" :isShowPag="false">
        <template #action="{ row }">
          <el-space v-auth="'business.setmel.recharge'">
            <!-- <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link>
            <sj-link custom-type="sblue" :underline="false" @click="edit(row)">编辑</sj-link>
            <sj-link custom-type="sred" :underline="false" @click="deletes(row)">删除</sj-link> -->
            <sj-link custom-type="sblue" :underline="false" @click="recharges(row, 1)">短信充值</sj-link>
            <sj-link custom-type="sblue" :underline="false" @click="recharges(row, 2)">语音充值</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h, withDirectives, resolveDirective } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElButton, ElMessage, ElMessageBox } from "element-plus";
import { getList, getRechargeInfo, recharge } from '@/api/operate/set-meal-management/package-balance/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog, closeDialog } from "@/components/ReDialog";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
import rechargeForm from './rechargeForm.vue'
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
import ReQrcode from "@/components/ReQrcode";
const elLoading = resolveDirective('loading')
const usePageVariablesStore = ref(usePageVariablesStoreHook())
const searchFrom = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});
const rechargeType = {
  1: '短信',
  2: '语音'
}
const searchFormRules = [
  {
    type: 'input', field: 'projectName', title: titles.projectName, value: null, props: {
      placeholder: prompt.projectName, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  // { type: "selection", align: "left" },

  { prop: 'id', label: titles.id, width: 100, fixed: 'left' },
  { prop: 'unityName', label: titles.unityName, minWidth: 150 },
  { prop: 'projectName', label: titles.projectName, minWidth: 150 },
  { prop: 'smsCount', label: titles.smsCount, minWidth: 100 },
  { prop: 'voiceCount', label: titles.voiceCount, minWidth: 100 },
  { slot: 'action', label: titles.action, width: 150, fixed: 'right' },
];
onMounted(() => {
  getTableList()
});
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm())
  key.value++
  getTableList()
}
const recharges = (row, type) => {
  addDialog({
    title: `${rechargeType[type]}充值`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    hideFooter: true,
    props: {
      formInline: {
        projectName: row?.projectName,
        projectId: row?.projectId,
        rType: type,
        aliasList: [],
        aliasCode: null,
      }
    },
    contentRenderer: ({ options, index }) => h(rechargeForm, {
      ref: formRef,
      onClickRecharge: () => {
        const FormRef = formRef.value.getRef();
        const formData = options.props.formInline;
        function chores() {
          message(`请等待支付信息同步`, {
            type: "success"
          });
          getTableList()
          closeDialog(options, index)
        }
        FormRef.validate(valid => {
          if (valid && !options.props?.isLoading) {
            options.props.isLoading = true;
            // showQRCode(debounce(chores, 1000, true), 'aaaa')

            recharge(formData).then(res => {
              showQRCode(debounce(chores, 1000, true), res.result.codeUrl)
            }).finally(() => {
              options.props.isLoading = false;
            })
          }
        });
      }
    }),
    openAutoFocus({ options, index }) {
      getRechargeInfo().then(res => {
        if (type == 1) { //短信
          options.props.formInline.aliasList = res.result.sms
        } else {
          options.props.formInline.aliasList = res.result.voice
        }
      })
    },
    // footerRenderer({ options, index }) {
    //   return h(
    //     "div",
    //     {
    //       class: "flex justify-end"
    //     },
    //     [
    //       h(
    //         ElButton,
    //         {
    //           text: false,
    //           bg: true,
    //           type: "primary",
    //           onClick: () => {
    //             const FormRef = formRef.value.getRef();
    //             const formData = options.props.formInline;
    //             function chores() {
    //               message(`请等待支付信息同步`, {
    //                 type: "success"
    //               });
    //               getTableList()
    //               closeDialog(options, index)
    //             }
    //             FormRef.validate(valid => {
    //               if (valid && !options.props?.isLoading) {
    //                 options.props.isLoading = true;
    //                 recharge(formData).then(res => {
    //                   // chores();
    //                   showQRCode(debounce(chores, 1000, true), res.result.codeUrl)
    //                 }).finally(() => {
    //                   options.props.isLoading = false;
    //                 })
    //               }
    //             });
    //           }
    //         },
    //         "立即充值"
    //       )
    //     ]
    //   );
    // },
  });
}
const showQRCode = (chores, codeUrl) => {
  const showLoading = ref(false)
  addDialog({
    title: `扫码支付`,
    width: "400px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => withDirectives(h('div', {
      class: 'flex-c flex-col'
    }, [h(ReQrcode, {
      text: codeUrl,
      tag: 'img'
    }),
    h('div', {
      class: 'mt-[10px] w-full flex-c'
    }, [h('img', {
      src: '/src/assets/images/wxpay.png',
      class: 'w-[34px] h-[20px] pr-[10px]'
    }), '请使用微信扫码支付'])
    ]), [[elLoading, showLoading.value]]),
    footerRenderer({ options, index }) {
      return h(
        "div",
        {
          class: "flex justify-end"
        },
        [h(
          ElButton,
          {
            text: false,
            bg: true,
            onClick: () => {
              closeDialog(options, index)
            }
          },
          "取消"
        ),
        h(
          ElButton,
          {
            text: false,
            bg: true,
            type: "primary",
            onClick: () => {
              showLoading.value = true
              setTimeout(() => {
                showLoading.value = false
                closeDialog(options, index)
                chores()
              }, 1000)
            }
          },
          "已完成付款"
        )
        ]
      );
    },
  });
}

const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
</script>
<style lang="scss" scoped></style>
